<?php

include_once($common_data_server."lib/php/captcha.php");

class form_question extends module
{
	var $captcha_error = 0;
	
// get_hash_code
function get_hash_code(){
	if($this->q_param["mode"]=="done" || $this->version==1)return 0;
    $all_params=$this->block_id.$this->lang_id;
    foreach($this->view_param as $vp)
       	$all_params.=$vp;
    if(is_array($this->q_param))
        foreach($this->q_param as $k=>$vp)
   	    	$all_params.=$vp.$_GET["print"].$_POST["print"];
	return md5($all_params);    
}
// Типа диспетчера - проверяем наличие шаблонов, объявляем основной шаблон и запускаем обработчика
function content_init(){
    global $common_data_server;
	//                               1        2       3       4        5          6           7          8            9               10               11                 12
    $this->control_types=array("","string","number","email","date","textarea","radio_group","select","checkbox","checkbox_group","radio_group_alt","checkbox_group_alt","break");
	
	$this->template_path="{$common_data_server}module_templates/form_question/{$this->view_param["template"]}/";
	if($this->q_param["mode"]=="filled"){
		if(!$this->set_template("filled.vtmpl")){
			$this->body=$this->error;
		}else{
			$this->body=$this->form_filled();
		}
	}elseif($this->q_param["mode"]=="done"){
		if(!$this->set_template("mail.vtmpl")){
			$this->body=$this->error;
		}else{
			$this->body=$this->form_done();
		}
	}else{
		if(!$this->set_template("form.vtmpl")){
			$this->body=$this->error;
		}else{
			$this->body=$this->form_fields();
		}
	}
}
// Вывод формы, которую будет заполнять пользователь
function form_fields()
{
	$this->template->setVar("hidden_fields","<input type=\"hidden\" name=\"mode".$this->tarea_id."\" value=\"done\">");
    $this->template->setVar('CAPTCHA_ERROR', $this->captcha_error);

	$question_rows=sql_select("SELECT FORM_QUESTION.* FROM FORM_QUESTION,CONTENT_MAP WHERE CONTENT_MAP.INF_BLOCK_ID={$this->block_id} AND FORM_QUESTION.CONTENT_ID=CONTENT_MAP.CONTENT_ID AND FORM_QUESTION.VERSION={$this->version} AND FORM_QUESTION.LANG_ID={$this->lang_id} ORDER BY FORM_QUESTION.QUESTION_ORDER");
	foreach($question_rows as $q_row)
	{
		$q_type=$q_row["QUESTION_TYPE"];
		if($q_type==6 || $q_type==7 || $q_type==9 || $q_type==10 || $q_type==11)
		{
			$options_rows = sql_select("SELECT * FROM FORM_OPTIONS WHERE CONTENT_ID=".$q_row["CONTENT_ID"]." AND VERSION=".$q_row["VERSION"]." ORDER BY OPTIONS_ORDER");
			$group = array();
			
			foreach($options_rows as $o_row)
			{
				$default="";
				$chb_name="";
				if($q_type==9 || $q_type==11)
				{
					$chb_name = "c".$o_row["FORM_OPTIONS_ID"];
				}
				
				if($q_type!=7)
				{
					$default_v = " checked";
				}
				else
				{
					$default_v = " selected";
				}
				
				////////////////////////////////
					
				if($o_row["IS_DEFAULT"] && !($this->captcha_error))
				{
					if($q_type!=7)
					{
						$default = $default_v;
					}
					else
					{
						$default = $default_v;
					}
				}
				elseif($this->captcha_error && $this->q_param[$chb_name."f".$q_row["CONTENT_ID"]."a"])
				{
					if($q_type == 9 || $q_type == 11)
					{
						$default = $default_v;
					}
					elseif($o_row["FORM_OPTIONS_ID"] == $this->q_param[$chb_name."f".$q_row["CONTENT_ID"]."a"])
					{
						$default = $default_v;
					}
				}
				
				////////////////////////////////
				
				$group[] = array(
					"name" => $o_row["NAME"],
					"system_name" => $chb_name."f".$q_row["CONTENT_ID"]."a".$this->tarea_id,
					"value" => $o_row["FORM_OPTIONS_ID"],
					"default" => $default,
					"is_mandatory" => $q_row["IS_MANDATORY"]);
			}
		}
		elseif($this->captcha_error)
		{
			$q_row["DEFAULT_VALUE"] = $this->q_param["f".$q_row["CONTENT_ID"]."a"];
		}
		
		$fields[]=array(
			"name"          => $q_row["TITLE"],
			"default_value" => $q_row["DEFAULT_VALUE"],
			"is_mandatory"  => $q_row["IS_MANDATORY"],
			"is_".$this->control_types[$q_row["QUESTION_TYPE"]] => 1,
			"system_name"   => "f".$q_row["CONTENT_ID"]."a".$this->tarea_id,
			"group"         => $group, 
			"alt_system_name" => "falt".$q_row["CONTENT_ID"]."a".$this->tarea_id,
			"alt_value"     => $this->q_param["falt".$q_row["CONTENT_ID"]."a"],
			"alt_check"		=> (($q_type == 10 && $this->q_param["f".$q_row["CONTENT_ID"]."a"] == "alt")? " checked" : "")
		);
	}
	$this->template->setLoop("fields",$fields);
	$this->template->setVar("form_name","form".$this->tarea_id);
    
    if( intval($this->view_param['captcha']) == 1)
    {
        $this->template->setVar( generateCaptchaCode() );
    }

	return $this->template->grab();
}
// Регистрация заполненной формы в БД, отсылка писем (если есть куда) и редирект на сообщение об успешном заполнении формы
function form_done()
{
    if( intval($this->view_param['captcha']) == 1)
    {
        $this->captcha_error = !(checkCaptchaCode( $this->q_param['captcha_id'], $this->q_param['captcha_value'] ));

        if($this->captcha_error)
        {
            if(!$this->set_template("form.vtmpl"))
            {
                return $this->error;
            }
            else
            {
                return $this->form_fields();
            }
        }
    }
	
	/////////////////////////////////
	
	
	$question_rows=sql_select("SELECT FORM_QUESTION.* FROM FORM_QUESTION,CONTENT_MAP WHERE CONTENT_MAP.INF_BLOCK_ID={$this->block_id} AND FORM_QUESTION.CONTENT_ID=CONTENT_MAP.CONTENT_ID AND FORM_QUESTION.VERSION={$this->version} AND FORM_QUESTION.LANG_ID={$this->lang_id} ORDER BY FORM_QUESTION.QUESTION_ORDER");
	
    $title_other = sql_select("SELECT VALUE FROM SYSTEM_WORD WHERE SYSTEM_NAME='SYSW_FORM_OTHER' AND LANG_ID=".$this->lang_id);

    insert_record('FORM_ANSWER', 
		array(
			array('name'=>'INF_BLOCK_ID','value'=>$this->block_id),
			array('name'=>'IP','value'=>$_SERVER["REMOTE_ADDR"]),
			array('name'=>'ANSWER_TIME','value'=>time())
			)
	);
	
	$answer_row=sql_select("SELECT MAX(FORM_ANSWER_ID) AS FORM_ANSWER_ID FROM FORM_ANSWER");

	
	foreach($question_rows as $q_row)
	{
		$value="";
		$q_type=$q_row["QUESTION_TYPE"];
		if(($q_type>=1 && $q_type<=5) || $q_type==8)
		{ 
			// Поля без опций
			insert_record('FORM_ANSWER_ON_QUESTION', array(array('name'=>'FORM_ANSWER_ID','value'=>$answer_row[0]["FORM_ANSWER_ID"]),
				array('name'=>'CONTENT_ID','value'=>$q_row["CONTENT_ID"]),
				array('name'=>'OPEN_ANSWER','value'=>$this->q_param["f".$q_row["CONTENT_ID"]."a"])));
			$value=$this->q_param["f".$q_row["CONTENT_ID"]."a"];
		}
		elseif($q_type==6 || $q_type==7)
		{ 
			// Радиогруппа и селект
			insert_record('FORM_ANSWER_ON_QUESTION', array(array('name'=>'FORM_ANSWER_ID','value'=>$answer_row[0]["FORM_ANSWER_ID"]),
				array('name'=>'CONTENT_ID','value'=>$q_row["CONTENT_ID"]),
				array('name'=>'FORM_OPTIONS_ID','value'=>$this->q_param["f".$q_row["CONTENT_ID"]."a"])));
			
			if($this->q_param["f".$q_row["CONTENT_ID"]."a"]!="")
			{
				$options_row=sql_select("SELECT NAME FROM FORM_OPTIONS WHERE FORM_OPTIONS_ID=".intval($this->q_param["f".$q_row["CONTENT_ID"]."a"]));
				$value=$options_row[0]["NAME"];
			}
		}
		elseif($q_type==9 || $q_type==11)
		{ 
			// Группа чекбоксов и она же с альтернативой
			$group=array();
			$options_rows=sql_select("SELECT * FROM FORM_OPTIONS WHERE CONTENT_ID=".$q_row["CONTENT_ID"]." AND VERSION=".$q_row["VERSION"]." ORDER BY OPTIONS_ORDER");
			foreach($options_rows as $o_row){
				insert_record('FORM_ANSWER_ON_QUESTION', array(array('name'=>'FORM_ANSWER_ID','value'=>$answer_row[0]["FORM_ANSWER_ID"]),
					array('name'=>'CONTENT_ID','value'=>$q_row["CONTENT_ID"]),
					array('name'=>'FORM_OPTIONS_ID','value'=>$o_row["FORM_OPTIONS_ID"]),
					array('name'=>'OPEN_ANSWER','value'=>$this->q_param["c".$o_row["FORM_OPTIONS_ID"]."f".$q_row["CONTENT_ID"]."a"])));
				$group[]=array("name"=>$o_row["NAME"],"value"=>$this->q_param["c".$o_row["FORM_OPTIONS_ID"]."f".$q_row["CONTENT_ID"]."a"]);
			}
			if($q_type==11 && $this->q_param["falt".$q_row["CONTENT_ID"]."a"]!=""){
				insert_record('FORM_ANSWER_ON_QUESTION', array(array('name'=>'FORM_ANSWER_ID','value'=>$answer_row[0]["FORM_ANSWER_ID"]),
					array('name'=>'CONTENT_ID','value'=>$q_row["CONTENT_ID"]),
					array('name'=>'OPEN_ANSWER','value'=>$this->q_param["falt".$q_row["CONTENT_ID"]."a"])));
				$group[]=array("name"=>$title_other[0]["VALUE"],"value"=>htmlspecialchars($this->q_param["falt".$q_row["CONTENT_ID"]."a"],ENT_QUOTES));
			}
		}elseif($q_type==10){ // Радиогруппа с альтернативой
			if($this->q_param["f".$q_row["CONTENT_ID"]."a"]!="alt"){
			insert_record('FORM_ANSWER_ON_QUESTION', array(array('name'=>'FORM_ANSWER_ID','value'=>$answer_row[0]["FORM_ANSWER_ID"]),
				array('name'=>'CONTENT_ID','value'=>$q_row["CONTENT_ID"]),
				array('name'=>'FORM_OPTIONS_ID','value'=>$this->q_param["f".$q_row["CONTENT_ID"]."a"])));

			}else{
			insert_record('FORM_ANSWER_ON_QUESTION', array(array('name'=>'FORM_ANSWER_ID','value'=>$answer_row[0]["FORM_ANSWER_ID"]),
				array('name'=>'CONTENT_ID','value'=>$q_row["CONTENT_ID"]),
				array('name'=>'OPEN_ANSWER','value'=>$this->q_param["falt".$q_row["CONTENT_ID"]."a"])));
			}
			if($this->q_param["f".$q_row["CONTENT_ID"]."a"]!=""){
				if($this->q_param["f".$q_row["CONTENT_ID"]."a"]!="alt" ){
					$options_row=sql_select("SELECT NAME FROM FORM_OPTIONS WHERE FORM_OPTIONS_ID=".intval($this->q_param["f".$q_row["CONTENT_ID"]."a"])." AND VERSION=".$q_row["VERSION"]);
					$value=$options_row[0]["NAME"];
				}else{
					$value=$title_other[0]["VALUE"].": ".$this->q_param["falt".$q_row["CONTENT_ID"]."a"];
				}
			}
		}
		$value=htmlspecialchars($value, ENT_QUOTES);
		$fields[]=array("name"=>$q_row["TITLE"],"value"=>$value,"is_mandatory"=>$q_row["IS_MANDATORY"],"is_".$this->control_types[$q_row["QUESTION_TYPE"]]=>1,"group"=>$group);
	}
	$this->template->setVar("ip",$_SERVER["REMOTE_ADDR"]);
	$this->template->setLoop("fields",$fields);
	$message=$this->template->grab();

	preg_match_all("/[\w\.-]+@[\w\.-]+\.\w\w+/",$this->view_param["email"],$matches);
	
	$site=sql_select("select * from SITE where SITE_ID={$this->site_id}");
	foreach($matches[0] as $email)
	{
		//обязательно ставить скобки после foreach, for, while, if и т.д.!!!
		//иначе это источник ошибок в будущем !!!
		post_mail(
			$email,
			"Администратор",
			"webmaster@".$_SERVER["SERVER_NAME"],
			$this->view_param["form_name"],
			"Сообщение с сайта \"{$site[0]["NAME"]}\"",
			$message,"w","k",1
		);
	}
	header("Location: index.php?mode{$this->tarea_id}=filled\n\n");
	exit();
}
// Сообщение об успешном заполнении формы
function form_filled(){
	return $this->template->grab();
}
// set_template
function set_template($tmpl){
	if(!$this->check_template($tmpl)){
		return 0;
	}else{
		$this->template=new vlibTemplate();
		$this->template->newTemplate($this->template_name);
		$this->template->setVar("tarea_id",$this->tarea_id);
		$this->template->setVar("title",$this->view_param["form_name"]);
		$this->template->setVar("descr",$this->view_param["descr"]);
		$this->title=$this->view_param["form_name"];
	}
	return 1;
}
// check_template
function check_template($tmpl){
	$full_name=$this->template_path.$tmpl;
	if(!file_exists($full_name)){
		$this->error.="Шаблон '{$this->template_path}{$tmpl}' отсутствует<br>";
		return 0;
	}
	$this->template_name=$full_name;
	return 1;
}

}
?>